<?php


namespace app\backend\controller\v1;

use app\backend\validate\UnitValidate;
use app\common\model\Unit as UnitModel;
use think\exception\ValidateException;

class Unit extends BaseController
{
    /**
     * 单元列表
     *
     * @return \think\Response
     */
    public function index()
    {
        // 资料库表
        // where条件
        $where = input('title');
        // 分页、排序等
        $page = input('page/d', 1);
        $pageSize = input('pageSize/d', 10);
        $list = UnitModel::order('id', 'asc')
            ->field('*')
            ->where(function ($query) use ($where) {
                $query->where('title', 'like', '%' . $where . '%');
            })
            ->page($page, $pageSize)
            ->select();
        $count = UnitModel::count();
        $maxpage = ceil($count / $pageSize);
        foreach ($list as &$value) {
            $value['grade_id'] = $value->grade->title;
            $value['course_id'] = $value->course->title;
            unset($value->grade);
            unset($value->course);
        }
        //获取列表
        return sucessMsg(200, '获取成功！', ['list' => $list, 'total' => $count,'page' => $maxpage]);
    }


    /**
     * 显示创建轮播表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $model = new UnitModel();
        $data = input();
        try {
            validate(UnitValidate::class)->scene('create')->check($data);
            if ($model->save($data)) {
                return sucessMsg(200, '创建成功！');
            }
            return errMsg(500, '创建失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update()
    {
        $id = input('id/d');
        if (empty($id)) {
            return errMsg(400, '请选择要修改的id！');
        }
        $data = input();
        try {
            validate(UnitValidate::class)->scene('update')->check($data);
            if (UnitModel::update($data, ['id' => $id])) {
                return sucessMsg(200, '修改成功！');
            }
            return errMsg(500, '修改失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete()
    {
        $id = input('id/d', 0);
        if (empty($id)) {
            return errMsg(400, '请选择要删除数据id！');
        }
        $data = UnitModel::find($id);
        if (empty($data)) {
            return errMsg(400, '要删除的数据为空！');
        }
        if (UnitModel::destroy($id)) {
            return sucessMsg(200, '删除成功！');
        }
        return errMsg(500, '删除失败！');
    }
}